// puppeteer 在安装时候会自动安装谷歌浏览器 而安装谷歌浏览器是需要翻墙的 所以会报错 可以先执行一段阻止安装谷歌浏览器的脚本或者是开蓝灯等vpn
//爬取电影封面和视频预告片
const puppeteer = require('puppeteer');
const base = `https://movie.douban.com/subject/`;
const doubanId = 26739551;

const sleep = time => {
    return new Promise(resolve => {
        setTimeout(resolve,time)
    })
}
;(async () =>{
    const browser = await puppeteer.launch({
        args:['--no-sandbox'],
        dumpio:false
    });
    const page = await browser.newPage();
    await page.goto(base + doubanId,{
        waitUntil:'networkidle2'
    })

    await sleep(1000);

    
    const result = await page.evaluate(() => {
        var $ = window.$;
        var it = $('.related-pic-video');
        if(it && it.length > 0) {
            var link = it.attr('href');
            var cover = it.find('img').attr('src');
            return {
                link,
                cover,
            }

            return {}
        }
    })

    let video;
    if(result.link) {
        await page.goto(result.link, {
            waitUntil:"networkidle2"
        })
        await sleep(2000)
        video = await page.evaluate(
            () => {
                var $ = window.$;
                var it = $('source');
                if(it && it.length){
                    return it.attr('src')
                }
                return ''
            }
        )
    }

    const data = {
        video,
        doubanId,
        cover:result.cover
    }

    browser.close();
    process.send(data)
    process.exit(0)



})()